1. MongoDB Introduction

Definition

MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. It provides high performance, high availability, and easy scalability. Documents in MongoDB can have different fields, and the structure can be changed over time.

Algorithm 1: Creating a Database :-
  • Step 1: Start MongoDB server
  • Step 2: Use the MongoDB shell command: use mydatabase
  • Step 3: Create a collection using: db.createCollection("mycollection")
  • Step 4: Verify database creation
  • Step 5: Stop
  • Example 1: Creating and Inserting Documents
    // Insert a document
    db.users.insertOne({
      name: "John Doe",
      age: 30,
      email: "john@example.com"
    })
    Algorithm 2: Querying Documents :-
  • Step 1: Connect to database
  • Step 2: Select collection using: db.collection
  • Step 3: Use find() method with query parameters
  • Step 4: Process results
  • Step 5: Close connection
  • Example 2: Querying Documents
    // Find documents
    db.users.find({
      age: { $gt: 25 },
      email: { $exists: true }
    }).sort({ name: 1 })
    Algorithm 3: Updating Documents :-
  • Step 1: Locate document to update
  • Step 2: Prepare update operation
  • Step 3: Use updateOne() or updateMany()
  • Step 4: Verify update success
  • Step 5: Handle any errors
  • Example 3: Updating Documents
                            // Update documents
    db.users.updateMany(
      { age: { $lt: 30 } },
      { $set: { status: "young" } }
    )